package com.ysx.student.fangyahao.day20210910.studentmanagement.service;

import com.ysx.student.fangyahao.day20210910.studentmanagement.dao.StudentDao;
import com.ysx.student.fangyahao.day20210910.studentmanagement.entity.ScoreEntity;
import com.ysx.student.fangyahao.day20210910.studentmanagement.entity.StundentEntity;


import java.util.ArrayList;

public class StudentService {


    private StudentDao dao=new StudentDao();

    public boolean addStudent(StundentEntity stundentEntity){
        if(stundentEntity == null){
            return false;
        }
        return dao.addStudent(stundentEntity);
    }

    public boolean matchStudent(String name,String password){
        return dao.matchStudent(name,password);
    }

    public boolean deleteStudent(String userName){
        if(dao.searchStudent(userName)==-1){
            return false;
        }
        return dao.deleteStudent(userName);
    }

    public boolean addScore(String userName, ScoreEntity score){
        int index=dao.searchStudent(userName);
        if(index==-1||score==null||dao.getArrayList().get(index).getScore()!=null){
            return false;
        }
        return dao.addScore(userName,score);
    }

    public boolean changeMathsScore(String userName, int score){
        int index = dao.searchStudent(userName);
        if(index==-1||score<0||score>100||dao.getArrayList().get(index).getScore()==null){
            return false;
        }
        return dao.changeMathsScore(userName,score);
    }

    public boolean printAllStudent(){
        if(dao.getArrayList()==null){
            return false;
        }
        return dao.printAllStudent();
    }

    public StundentEntity getStudentByMaxScoreOfMaths(){
        if(dao.getArrayList()==null){
            return null;
        }
        return dao.getStudentByMaxScoreOfMaths();
    }

    public StundentEntity getStudentByMaxAverage(){
        if(dao.getArrayList()==null){
            return null;
        }
        return dao.getStudentByMaxAverage();
    }

    public ArrayList<StundentEntity> sortStudentByAverage(){
        ArrayList<StundentEntity> arrayList = dao.getArrayList();
        for(int index=0;index<arrayList.size()-1;index++){
            if(arrayList.get(index).getScore()==null){
                arrayList.remove(index);
                index--;
                continue;
            }
            int min=index;
            for(int inner=index+1;inner<arrayList.size();inner++){
                if(arrayList.get(inner).getScore()==null){
                    arrayList.remove(inner);
                    inner--;
                    continue;
                }
                if(dao.getStudentAverage(min)>dao.getStudentAverage(inner)){
                    min=inner;
                }
            }
            StundentEntity stundent = arrayList.get(min);
            arrayList.set(min,arrayList.get(index));
            arrayList.set(index,stundent);
        }
        return arrayList;
    }


}
